package com.bzxgc.sgwer.controller.menu;

import com.bzxgc.sgwer.common.util.JsonResult;
import com.bzxgc.sgwer.common.util.JsonUtils;
import com.bzxgc.sgwer.entity.menu.Menu;
import com.bzxgc.sgwer.service.menu.MenuService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/menu")
public class MenuController {

    @Autowired
    private MenuService menuService;

    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        List<Menu> menuList = menuService.getAllOneMenuNoChildren();
        request.setAttribute("parentList", menuList);
        return "menu/save";
    }

    @RequestMapping("/update/{id}")
    public String update(@PathVariable("id") Long id, HttpServletRequest request) {
        Menu menu = menuService.getMenuById(id);
        List<Menu> menuList = menuService.getAllOneMenuNoChildren();
        request.setAttribute("menu", menu);
        request.setAttribute("parentList", menuList);
        return "menu/save";
    }

    @RequestMapping("/ajax/save")
    @ResponseBody
    public JsonResult ajaxSave(Menu menu) {
        if (menu.getId() == null) {
            menuService.addMenu(menu);
        } else {
            menuService.updateMenu(menu);
        }
        return JsonResult.success("保存成功");
    }

    @RequestMapping("/ajax/delete")
    @ResponseBody
    public JsonResult ajaxDelete(@RequestParam("ids") Long[] ids) {
        menuService.updateMenuStatus(ids, 2);
        return JsonResult.success("删除成功");
    }

    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        List<Menu> menuList = menuService.getAllMenu();
        String json = JsonUtils.objectToJson(menuList);
        request.setAttribute("json", json);
        return "menu/list";
    }

    @RequestMapping("/ajax/list")
    @ResponseBody
    public JsonResult ajaxList() {
        List<Menu> menuList = menuService.getAllMenu();
        String json = JsonUtils.objectToJson(menuList);
        return JsonResult.success("获取成功", json);
    }
}
